package com.ruike.alisurface.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Environment;
import android.view.View;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 屏幕截图类
 * Created by czb on 2020-04-15.
 */

public class ScreenshotsUtils {


    public static Bitmap activityShot(Activity activity) {
    /*获取windows中最顶层的view*/
        View view = activity.getWindow().getDecorView();
        //允许当前窗口保存缓存信息
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bitmap =view.getDrawingCache();

        Bitmap returnBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight());

        //销毁缓存信息
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(false);

        return returnBitmap;
    }

    public static File saveBitmap(Bitmap bitmap) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Screenshots");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        long systemTime = System.currentTimeMillis();
        String fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date(systemTime));

        String imgName ="Screenshots-" + fileName+ ".png";
        File file = new File(appDir, imgName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


        return  file;
    }

}
